// 前端消息通知集成示例

// 1. 定时获取未读消息数量
function getUnreadMessageCount() {
    fetch('/vegetable-cloud/sys/message/unreadCount', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'token': localStorage.getItem('token')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            // 更新消息铃铛上的数字
            const msgCountElement = document.getElementById('message-count');
            if (msgCountElement) {
                msgCountElement.textContent = data.data;
                msgCountElement.style.display = data.data > 0 ? 'block' : 'none';
            }
        }
    })
    .catch(error => {
        console.error('获取未读消息数量失败:', error);
    });
}

// 2. 获取消息列表
function getMessageList(page = 1, limit = 10) {
    fetch(`/vegetable-cloud/sys/message/list?page=${page}&limit=${limit}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'token': localStorage.getItem('token')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            renderMessageList(data.data.list);
        }
    })
    .catch(error => {
        console.error('获取消息列表失败:', error);
    });
}

// 3. 渲染消息列表
function renderMessageList(messages) {
    const messageListElement = document.getElementById('message-list');
    if (!messageListElement) return;

    let html = '';
    messages.forEach(message => {
        const readClass = message.isRead === 1 ? 'read' : 'unread';
        html += `
            <div class="message-item ${readClass}" data-id="${message.messageId}">
                <div class="message-header">
                    <span class="message-title">${message.title}</span>
                    <span class="message-time">${formatTime(message.createTime)}</span>
                </div>
                <div class="message-content">${message.content}</div>
                <div class="message-actions">
                    ${message.isRead === 0 ? 
                        `<button class="btn-mark-read" onclick="markAsRead(${message.messageId})">标记已读</button>` : 
                        ''}
                    <button class="btn-delete" onclick="deleteMessage(${message.messageId})">删除</button>
                </div>
            </div>
        `;
    });

    messageListElement.innerHTML = html;
}

// 4. 标记消息为已读
function markAsRead(messageId) {
    fetch(`/vegetable-cloud/sys/message/read/${messageId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'token': localStorage.getItem('token')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200 && data.data) {
            // 重新加载消息列表
            getMessageList();
            // 重新获取未读消息数量
            getUnreadMessageCount();
        }
    })
    .catch(error => {
        console.error('标记消息为已读失败:', error);
    });
}

// 5. 删除消息
function deleteMessage(messageId) {
    if (!confirm('确定要删除这条消息吗？')) {
        return;
    }

    fetch(`/vegetable-cloud/sys/message/delete/${messageId}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'token': localStorage.getItem('token')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200 && data.data) {
            // 重新加载消息列表
            getMessageList();
            // 重新获取未读消息数量
            getUnreadMessageCount();
        }
    })
    .catch(error => {
        console.error('删除消息失败:', error);
    });
}

// 6. 格式化时间
function formatTime(timeStr) {
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) {
        return '刚刚';
    } else if (minutes < 60) {
        return `${minutes}分钟前`;
    } else if (hours < 24) {
        return `${hours}小时前`;
    } else {
        return `${days}天前`;
    }
}

// 7. 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 每30秒获取一次未读消息数量
    setInterval(getUnreadMessageCount, 30000);
    
    // 页面加载时获取一次
    getUnreadMessageCount();
});